﻿using System;
using System.Linq;
using System.Net;
using System.Web.Mvc;
using Matrix.MaKaYunShang.BLL;
using Matrix.MaKaYunShang.Model;
using Matrix.MaKaYunShang.Model.Dto;
using Newtonsoft.Json;

namespace Matrix.MaKaYunShang.McMagWeb.Controllers
{
    [Authorization]
    public class RolePermissionController : BaseController
    {
        #region 列表
        
        [PermissionFilter]
        public ActionResult List()
        {
            return View();
        }

        [HttpPost]
        public JsonResult Listing(int draw, int start, int length)
        {
            int order;
            int.TryParse(Request["order[0][column]"], out order);
            string direction = Request["order[0][dir]"];
            var orderByColumns = new[] { "RoleName" };
            string search = Request["search[value]"];
            int pageIndex = (start / length) + 1;

            TableDataViewDto<ViewMcRoleDto> theList = McRolesBLL.Instance.GetPagingListForPermission(draw, pageIndex, length, SqlSafe(search),
                orderByColumns[order] + " " + direction);

            JsonResult jsonResult = Json(theList);
            jsonResult.MaxJsonLength = int.MaxValue;

            return jsonResult;
        }
        #endregion
        
        #region 修改

        public ActionResult Update(int id)
        {
            if (id <= 0) return new HttpStatusCodeResult(HttpStatusCode.BadRequest);

            InitiSet();

            var shopId = CurrentUser.ShopId;
            var model = new RolePermissionDto
            {
                RoleId = id,
                RoleName = McRolesBLL.Instance.GetModel(id).Name,
                ShopId = CurrentUser.ShopId,
                ListModules = JsonConvert.SerializeObject(McRoleModulePermissionBLL.Instance.GetModelListByRoleIdAndShopId(shopId, id))
            };

            return View(model);
        }

        [HttpPost]
        public ActionResult Update(FormCollection collection, RolePermissionDto model, int[] modules)
        {
            var resultClearUp = McRoleModulePermissionBLL.Instance.ClearSetByRoleIdAndShopId(CurrentUser.ShopId,
                model.RoleId);
            if (!resultClearUp) return new HttpStatusCodeResult(HttpStatusCode.InternalServerError);

            if (modules == null || modules.Count() <= 0) return RedirectToAction("List", "RolePermission");

            foreach (var moduleId in modules)
            {
                var resultInserting = InsertRolePermissionData(moduleId, model.RoleId, CurrentUser.ShopId);
                if (!resultInserting) return new HttpStatusCodeResult(HttpStatusCode.InternalServerError);
            }

            return RedirectToAction("List", "RolePermission");
        }

        #endregion

        #region Private Functions 自用函数

        private bool InsertRolePermissionData(int moduleId, int roleId, int shopId)
        {
            var permissionModel = new McRoleModulePermission
            {
                Updated = DateTime.Now,
                UpdatedBy = CurrentUser.AccountId,
                Created = DateTime.Now,
                CreatedBy = CurrentUser.AccountId,
                IsAllowAccess = true,
                ModuleId = moduleId,
                RoleId = roleId,
                ShopId = shopId
            };

            return McRoleModulePermissionBLL.Instance.Add(permissionModel) > 0;
        }

        private void InitiSet()
        {
            ViewBag.Modules = new SelectList(McModulesBLL.Instance.GetModuleList(), "Id", "Name");
        }

        #endregion

    }
}